<template>
    <el-main style="padding: 10px">
        <el-button type="primary" icon="Plus" size="default" @click="onNewAdd">新增</el-button>

        <el-table default-expand-all :height="tableHeight" style="margin-top: 10px" :data="tableData" row-key="menuId"
            border stripe>
            <el-table-column label="菜单名称" prop="title"></el-table-column>
            <el-table-column label="菜单图标" prop="icon">
                <template #default="scope">
                    <el-icon v-if="scope.row.icon">
                        <component :is="scope.row.icon"></component>
                    </el-icon>
                </template>
            </el-table-column>
            <el-table-column label="类型" prop="type">
                <template #default="scope">
                    <el-tag v-if="scope.row.type == '0'" type="danger" size="default">目录</el-tag>
                    <el-tag v-if="scope.row.type == '1'" type="success" size="default">菜单</el-tag>
                    <el-tag v-if="scope.row.type == '2'" type="primary" size="default">按钮</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="路由地址" prop="path"></el-table-column>
            <el-table-column label="权限编码" prop="code">
                <template #default="scope">
                    <el-popover content="点击复制到剪贴板" placement="left-start">
                        <template #reference>
                            <span @click="onCopyPermissionCode(scope.row.code)" class="permission-code">
                                {{ scope.row.code }}
                            </span>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="220">
                <template #default="scope">
                    <el-button type="primary" size="default" @click="onEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" size="default" @click="onDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增或编辑弹框 -->
        <SysDialog :title="dialog.title" :width="dialog.width" :visible="dialog.visible" @on-close="onDialogClose"
            @on-confirm="onSubmit">
            <template v-slot:content>
                <el-form :model="menuForm" ref="menuFormRef" :rules="rules" :inline="false" size="default">
                    <el-form-item label="菜单类型" prop="type">
                        <el-radio-group v-model="menuForm.type">
                            <el-radio :label="'0'">目录</el-radio>
                            <el-radio :label="'1'">菜单</el-radio>
                            <el-radio :label="'2'">按钮</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-row :gutter="24">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="上级菜单" prop="parentId">
                                <el-tree-select style="width: 100%" placeholder="选择上级菜单" v-model="menuForm.parentId"
                                    :data="menuTreeList" @check-change="onTreeCheckChange" :render-after-expand="false"
                                    check-strictly show-checkbox />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item label="菜单名称" prop="title">
                                <el-input v-model="menuForm.title"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row v-if="menuForm.type !== '2'" :gutter="24">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="菜单图标" prop="icon">
                                <el-input v-model="menuForm.icon" readonly placeholder="使用【选择】按钮选择图标">
                                    <template #prepend>
                                        <el-icon :size="20">
                                            <component :is="menuForm.icon"></component>
                                        </el-icon>
                                    </template>
                                    <template #append>
                                        <IconSelectorDialog @clickIcon="onClifckIcon">
                                        </IconSelectorDialog>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item label="路由名称" prop="name">
                                <el-input v-model="menuForm.name"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="12" :offset="0">
                            <el-form-item label="菜单序号" prop="orderNum">
                                <el-input-number v-model="menuForm.orderNum" :min="1" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item label="权限字段" prop="code">
                                <el-input v-model="menuForm.code"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col v-if="menuForm.type !== '2'" :span="12" :offset="0">
                            <el-form-item label="路由地址" prop="path">
                                <el-input v-model="menuForm.path"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="menuForm.type === '1'" :span="12" :offset="0">
                            <el-form-item label="组件路径" prop="url">
                                <el-input v-model="menuForm.url"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </template>
        </SysDialog>
    </el-main>

</template>

<script setup lang="ts">
import SysDialog from "@/components/SysDialog.vue"
import useDialog from "../../../hooks/useDialog"
import { ElMessage, type FormInstance } from "element-plus"
import { nextTick, onMounted, reactive, ref } from "vue"
import { MenuApi } from "../../../api/menu"
import useInstance from '../../../hooks/useInstance'
import IconSelectorDialog from "../../../components/IconSelectorDialog.vue"

// 表单ref属性
const menuFormRef = ref<FormInstance>()
// 弹框属性
const { dialog, onDialogClose, onDialogShow } = useDialog()

// 查询上级菜单
const menuTreeList = ref([])
const queryParentMenuTree = async () => {
    let res = await MenuApi.listParentTree()
    if (res && res.code == 200) {
        menuTreeList.value = res.data
    }
};
// 新增按钮
const onNewAdd = () => {
    dialog.title = '新增菜单'
    dialog.width = 888
    // 查询上级菜单
    queryParentMenuTree()

    Object.assign(menuForm, {
        menuId: '',
        parentId: '',
        title: '',
        code: '',
        name: '',
        path: '',
        url: '',
        type: '0',
        icon: 'Money',
        parentName: '',
        orderNum: ''
    })

    // 显示弹框
    nextTick(() => {
        menuFormRef.value?.resetFields()
    })
    onDialogShow()
}
// 表单绑定的对象
let menuForm = reactive({
    menuId: '',
    parentId: '',
    title: '',
    code: '',
    name: '',
    path: '',
    url: '',
    type: '0',
    icon: 'Money',
    parentName: '',
    orderNum: ''
})

let dialogType: 'newAdd' | 'edit' = 'newAdd'
const onSubmit = () => {
    menuFormRef.value?.validate(async validate => {
        if (validate) {
            let res = null
            if (dialogType === 'newAdd') {
                res = await MenuApi.newAdd(menuForm)
            } else if (dialogType === 'edit') {
                res = await MenuApi.edit(menuForm)
            }
            if (res && res.code === 200) {
                onDialogClose()
                queryTableData()
                ElMessage.success(res.msg)
            }
        }
    })
}

const onTreeCheckChange = (item: any) => {
    menuForm.parentName = item.title
}

const onEdit = async (menu: any) => {
    dialog.title = '编辑菜单'
    dialogType = 'edit'
    dialog.width = 888

    // 显示弹框
    onDialogShow()
    // 清空表单
    menuFormRef.value?.resetFields()
    // 查询上级菜单
    await queryParentMenuTree()

    nextTick(() => {
        Object.assign(menuForm, menu)
    })
}

const { global } = useInstance()
const onDelete = async (menu: any) => {
    const confirm = await global.$jagochanConfirm(`确定删除【${menu.title}】菜单吗？`)
    if (confirm) {
        let res = await MenuApi.delete(menu.menuId)
        if (res && res.code == 200) {
            ElMessage.success(res.msg)
            queryTableData()
        } else {
            ElMessage.error(res.msg)
        }
    }
}

const tableData = ref([])
const queryTableData = async () => {
    const res = await MenuApi.listMenuTree()
    if (res && res.code === 200) {
        tableData.value = res.data
    }
}

const onCopyPermissionCode = async (text: string) => {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
}

const tableHeight = ref(0)
onMounted(() => {
    nextTick(() => {
        tableHeight.value = window.innerHeight - 218
    })
    queryTableData()
})

const onClifckIcon = (icon: string) => {
    menuForm.icon = icon
}

// 表单验证规则
const rules = reactive({
    parentId: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "选择上级菜单",
        },
    ],
    title: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "填写菜单名称",
        },
    ],
    code: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "填写权限字段",
        },
    ],
    name: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "填写路由名称",
        },
    ],
    path: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "填写路由地址",
        },
    ],
    url: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "填写组件路径",
        },
    ],
    type: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "选择菜单类型",
        },
    ],
    icon: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "填写菜单图标",
        },
    ],
    orderNum: [
        {
            required: true,
            trigger: ["blur", "change"],
            message: "填写菜单序号",
        },
    ],
});
</script>

<style scoped>
.permission-code:hover {
    cursor: pointer;
    font-weight: 800;
}
</style>
